package server

import (
	"fmt"
	"go-test/src/com/miao/server/context"
	"go-test/src/com/miao/server/task"
	"log"
	"net"
	"os"
	"time"
)



/*服务端，启动！*/
func StartServer(port string,ctx *context.GroupContext){
	tcpAddr, err := net.ResolveTCPAddr("tcp4", port)
	CheckError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	CheckError(err)
	defer listener.Close()
	Log(listener.Addr().String(),"服务端已启动")
	//初始化groupContext
	ctx.InitGroupContext()
	for {
		conn, err := listener.AcceptTCP()
		if err != nil {
			continue
		}
		//设置读取缓冲2048个字节
		conn.SetReadBuffer(2048)
		Log(conn.RemoteAddr().String(), " tcp connect success")
		//初始化channel
		channelContext:=context.InitChannelContext(conn,ctx)
		ctx.Connections.Add(channelContext)
		//处理连接成功后监听
		task.HandleConnectedTask(channelContext)
		go HandleConnection(channelContext)

	}

}


//处理连接
func HandleConnection(channelContext *context.ChannelContext) {
	//声明一个临时缓冲区，用来存储被截断的数据
	tmpBuffer := make([]byte, 0)
	//ch :=make(chan []byte)
	buffer := make([]byte, 2048)
	//处理解码和编码通道
	go channelContext.ReadChannelTask(channelContext.ReadChan,channelContext.GroupContext.PacketHandler)
	go channelContext.SendChannelTask(channelContext.SendChan,channelContext.GroupContext.PacketHandler)
	for {
		n, err := channelContext.Conn.Read(buffer)
		if err != nil {
			Log(channelContext.Conn.RemoteAddr().String(), " connection error: ", err)
			//处理连接关闭
			task.HandleCloseTask(channelContext)
			return
		}
		//心跳检测,最近一次收到消息的时间
		if n!=0{
			channelContext.LatestTimeOfReceivedData=time.Now().Unix()
		}

		//Log(channelContext.Conn.RemoteAddr().String(), "receive data string:\n", string(buffer[:n]))
		//处理解码
		tmpBuffer=channelContext. HandleDecode(channelContext.GroupContext.PacketHandler,append(tmpBuffer, buffer[:n]...))
	}
	defer channelContext.Conn.Close()
}



func Log(v ...interface{}) {
	log.Println(v...)
}

func CheckError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}



